<?php

/**
 * uniBoard TASK: Hourly Cleaning
 *
 * Light and fast forum solution for web 2.0-like communities.
 *
 * @package		uniBoard
 * @author		Rafał Pitoń
 * @license		http://www.gnu.org/licenses/gpl-3.0.html
 * @since		Version 0.1
 * 
 * ------------------------------------------------------------------------
 * 
 * $Date: 2010-09-06 01:45:14 +0000 (Mon, 06 Sep 2010) $
 * $Revision: 59 $
 * $Author: rafio.xudb@gmail.com $
 */

// ------------------------------------------------------------------------

class task{
	
	// ------------------------------------------------------------------------

	/**
	 * Initialise Task
	 *
	 * @param object $appCore
	 */
	
	function __construct( $appCore){
		
		// Kill outdated Admin Sessions
		$appCore -> db -> delete( 'sessions_admin', 'session_last_active < \'' . ( $appCore -> time - $appCore -> conf['session_auth_timeout']) . '\'');
		
		// Get Expired User sessions 
		$appCore -> db -> query( 'SELECT user_id, crawler_id, session_last_active, session_ip
		FROM ' . DB_PREFIX . 'sessions
		WHERE session_last_active < \'' . ( $appCore -> time - $appCore -> conf['session_auth_timeout']) . '\' AND user_id > 0');
		
		// Expired User Sessions
		$users_visits = array();
		
		// Expired Bot Sessions
		$bots_visits = array();
		
		// Select users
		while ( $user_result = $appCore -> db -> fetch_array())
		{
			// Bot?
			if ( $user_result[1] > 0)
			{
				// User in array?
				if ( !isset( $bots_visits[$user_result[1]]) || $bots_visits[$user_result[1]] < $user_result[2])
				{
					// Add us to array or update existing record
					$bots_visits[$user_result[1]] =  $user_result[2];
				}
			}
			else
			{
				// User in array?
				if ( !isset( $users_visits[$user_result[0]]) || $users_visits[$user_result[0]][0] < $user_result[2])
				{
					// Add us to array or update existing record
					$users_visits[$user_result[0]] = array(
						0 	=> $user_result[2],
						1	=> $user_result[3]
					);
				}
			}
		}
		
		// Kill outdated User Sessions
		$appCore -> db -> delete( 'sessions', 'session_last_active < \'' . ( $appCore -> time - $appCore -> conf['session_auth_timeout']) . '\'');

		// Update Users?
		if ( !empty( $users_visits))
		{
			// Reiterate users
			foreach ( $users_visits as $user_id => $visit_data)
			{
				$appCore -> db -> update( array( 'user_last_date' => $visit_data[0], 'user_last_ip' => $appCore -> strEscape( $visit_data[1])), 'users', 'user_id = \'' . $user_id . '\'');
			}
		}
		
		// Update Bots?
		if ( !empty( $bots_visits))
		{
			// Reiterate users
			foreach ( $bots_visits as $bot_id => $visit_date)
			{
				$appCore -> db -> update( array( 'crawler_last_visit' => $visit_date), 'crawlers', 'crawler_id = \'' . $bot_id . '\'');
			}
		}
				
	}
	
}